import React, {useState} from 'react';
import {Text, View, StyleSheet} from 'react-native';
import {
  Button,
  Modal,
  Flex,
  Toast,
  List,
  Switch,
  WingBlank,
  WhiteSpace,
} from '@ant-design/react-native';
import {ScrollView} from 'react-native-gesture-handler';
import {IconX} from '@/rcomponents/iconx';
import RadioButtonGroup from '@/rcomponents/radioButtonGroup';
import Colors from '@/Themes/Colors';
import NumbericInputItem from '@/rcomponents/numbericInputItem';
import MaterialReturnStore from './materialReturnStore';
import ShipRequesterScan from './components/shipRequesterScan';
import RnBarcodeScanner from './components/rnBarcodeScanner';
import ReturnResultPage from './returnResultPage';
import FlexTextField from '@/rcomponents/flexTextField';
import RackConfirmButton from './components/rackConfirmButton';
import rackMaterialStore from './components/rackMaterialStore';
import {MaterialReturnRoute} from './routeDef';

const styles = StyleSheet.create({
  centerView: {
    alignItems: 'center',
  },
  boldLabel: {
    fontWeight: 'bold',
  },
  soLabel: {
    fontSize: 16,
    marginRight: 8,
  },
  listHeader: {paddingVertical: 10},
  headerText: {
    fontSize: 16,
    paddingLeft: 10,
  },
  filterBtnFlex: {
    justifyContent: 'flex-end',
    paddingRight: 10,
  },
  partFlex: {
    flex: 3,
  },
  lightingText: {
    color: Colors.green500,
  },
  warningText: {
    color: Colors.red400,
  },
});

function ReturnOrderScanButton() {
  const returnedStore = MaterialReturnStore.useStore();
  const [scanVisible, setScanVisible] = useState(false);
  return (
    <Button
      onPress={() => {
        setScanVisible(true);
      }}>
      <Flex>
        <Text style={styles.soLabel}>发料单号:</Text>
        {returnedStore.shipOrder.name ? (
          <Text>{returnedStore.shipOrder.name}</Text>
        ) : (
          <IconX
            origin="MATERIALCOMMUNITY"
            name="credit-card-scan-outline"
            size={28}
          />
        )}
      </Flex>
      <Modal
        visible={scanVisible}
        onClose={() => {
          setScanVisible(false);
        }}>
        <RnBarcodeScanner
          scanProcessing={returnedStore.getReturnShipOrder.loading}
          onBarCodeRead={async (barcode) => {
            const error = await returnedStore.getReturnShipOrder(barcode);
            if (error) {
              Toast.fail('条码获取发料单信息失败, 请重试');
            }
            setScanVisible(false);
          }}
          onExitScan={() => {
            setScanVisible(false);
          }}
        />
      </Modal>
    </Button>
  );
}

function MaterialScanButton({msbStyles = {}, buttonType}) {
  const returnedStore = MaterialReturnStore.useStore();
  const [scanVisible, setScanVisible] = useState(false);
  const [returnedModal, setReturnedModal] = useState({
    visible: false,
    materialFailMsg: '',
    returnedOne: {
      part_no: '',
      name: '',
      serial_no: '',
      batch_no: '',
      returnable_qty: 0,
      returning_qty: 1,
      available: false,
    },
  });
  const handleReturnedConfirm = () => {
    returnedStore.slotReturnOne(returnedModal.returnedOne);
    handleReturnedClose();
  };
  const handleReturnedClose = () => {
    setReturnedModal({visible: false, returnedOne: {}});
  };
  return (
    <Button
      type={buttonType}
      key="scan"
      onPress={() => {
        setScanVisible(true);
      }}>
      <IconX name="scan" origin="ionicons" />
      扫件
      <Modal
        visible={scanVisible}
        onClose={() => {
          setScanVisible(false);
        }}>
        <RnBarcodeScanner
          scanProcessing={returnedStore.getMaterialByBarcode.loading}
          onBarCodeRead={async (barcode) => {
            const materialRes = await returnedStore.getMaterialByBarcode(
              barcode,
            );
            setScanVisible(false);
            if (materialRes.errorCode) {
              Toast.fail('条码获取料件信息失败, 请重试');
            } else {
              const orderItems = returnedStore.shipDetails.filter(
                (rts) => rts.batch_no === materialRes.batch_no,
              );
              let failMsg = null;
              let {returnedOne} = returnedModal;
              if (orderItems.length > 0) {
                if (
                  orderItems.filter(
                    (item) => item.ship_qty - item.returned_qty > 0,
                  ).length === 0
                ) {
                  failMsg = '此批次航材在此发料单无可用数量';
                } else {
                  const nonReturnQty = orderItems.reduce(
                    (acc, cur) => acc + cur.ship_qty - cur.returned_qty,
                    0,
                  );
                  returnedOne = {
                    part_no: orderItems[0].part_no,
                    name: orderItems[0].name,
                    serial_no: orderItems[0].serial_no,
                    batch_no: orderItems[0].batch_no,
                    returnable_qty: nonReturnQty,
                    returning_qty: 1,
                    available: true,
                  };
                }
              } else {
                failMsg = '此批次航材未在此发料单进行发料';
              }
              setReturnedModal({
                visible: true,
                materialFailMsg: failMsg,
                returnedOne,
              });
            }
          }}
          onExitScan={() => {
            setScanVisible(false);
          }}
        />
      </Modal>
      <Modal popup visible={returnedModal.visible} animationType="slide-up">
        {returnedModal.materialFailMsg ? (
          <View style={styles.centerView}>
            <WhiteSpace />
            <Text style={styles.boldLabel}>
              {returnedModal.materialFailMsg}
            </Text>
            <WhiteSpace />
            <Flex>
              <Button type="primary" onPress={handleReturnedClose}>
                关闭
              </Button>
            </Flex>
            <WhiteSpace />
          </View>
        ) : (
          <>
            <Flex>
              <Text style={styles.boldLabel}>
                {returnedModal.returnedOne.part_no}
              </Text>
            </Flex>
            <Flex>
              <FlexTextField
                label="名称"
                fieldValue={returnedModal.returnedOne.name}
                labelStyle={styles.boldLabel}
              />
            </Flex>
            <Flex>
              <FlexTextField
                label="序号"
                fieldValue={returnedModal.returnedOne.serial_no}
                labelStyle={styles.boldLabel}
              />
              <FlexTextField
                label="系统批次号"
                fieldValue={returnedModal.returnedOne.batch_no}
                labelStyle={styles.boldLabel}
              />
            </Flex>
            <Flex>
              <FlexTextField
                label="可退数量"
                fieldValue={returnedModal.returnedOne.returnable_qty}
                labelStyle={styles.boldLabel}
              />
            </Flex>
            <Flex>
              <NumbericInputItem
                label="退料数"
                minValue={0}
                maxValue={returnedModal.returnedOne.returnable_qty}
                value={returnedModal.returnedOne.returning_qty}
                onChange={(num) => {
                  if (Number.isNaN(num) || num === '' || num === null) {
                    return;
                  }
                  setReturnedModal({
                    ...returnedModal,
                    returnedOne: {
                      ...returnedModal.returnedOne,
                      returning_qty: num,
                    },
                  });
                }}
              />
              <FlexTextField
                label="可用"
                fieldValue={
                  <Switch
                    checked={returnedModal.returnedOne.available}
                    onChange={(checked) =>
                      setReturnedModal({
                        ...returnedModal,
                        returnedOne: {
                          ...returnedModal.returnedOne,
                          available: checked,
                        },
                      })
                    }
                  />
                }
                labelStyle={styles.boldLabel}
              />
            </Flex>
            <Flex>
              <Flex.Item>
                <Button onPress={handleReturnedClose}>取消</Button>
              </Flex.Item>
              <Flex.Item>
                <Button type="primary" onPress={handleReturnedConfirm}>
                  确定
                </Button>
              </Flex.Item>
            </Flex>
          </>
        )}
      </Modal>
    </Button>
  );
}

function AerialMaterialReturn({navigation}) {
  const returnedStore = MaterialReturnStore.useStore();
  const rackmatStore = rackMaterialStore.useStore();
  const [filterOpt, setFilterOpt] = useState('all');
  const hasReturnings =
    returnedStore.shipDetails.filter((spd) => spd.returning_qty > 0).length > 0;
  const handleReturnConfirm = async () => {
    await returnedStore.postReturnItems();
    navigation.navigate(ReturnResultPage.routeName);
  };
  return (
    <>
      <Flex>
        <Flex.Item>
          <ShipRequesterScan requesterType="退料人" />
        </Flex.Item>
        <Flex.Item>
          <ReturnOrderScanButton />
        </Flex.Item>
      </Flex>
      <ScrollView>
        <List
          renderHeader={
            <Flex style={styles.listHeader}>
              <Flex.Item>
                <Text style={styles.headerText}>发料记录列表</Text>
              </Flex.Item>
              <Flex.Item>
                <Flex style={styles.filterBtnFlex}>
                  <RadioButtonGroup
                    value={filterOpt}
                    options={[
                      {value: 'all', text: '全部'},
                      {value: 'selected', text: '已选'},
                    ]}
                    onChange={(val) => setFilterOpt(val)}
                  />
                </Flex>
              </Flex.Item>
            </Flex>
          }>
          {returnedStore.shipDetails
            .filter((shd) => filterOpt === 'all' || shd.returning_qty > 0)
            .map((shd) => (
              <List.Item key={shd.id}>
                <Flex>
                  <Flex.Item style={styles.partFlex}>
                    <Text style={styles.soLabel}>{shd.part_no}</Text>
                  </Flex.Item>
                  <FlexTextField
                    label="已发"
                    fieldValue={shd.ship_qty}
                    labelStyle={styles.boldLabel}
                    valueStyle={styles.lightingText}
                  />
                  <FlexTextField
                    label="已退"
                    fieldValue={shd.returned_qty}
                    labelStyle={styles.boldLabel}
                    valueStyle={styles.warningText}
                  />
                  <WingBlank>
                    <FlexTextField
                      label="可用"
                      fieldValue={
                        <Switch
                          checked={shd.available}
                          onChange={(checked) =>
                            returnedStore.changeReturnDetail(
                              shd.id,
                              'available',
                              checked,
                            )
                          }
                        />
                      }
                      labelStyle={styles.boldLabel}
                    />
                  </WingBlank>
                </Flex>
                <Flex>
                  <FlexTextField
                    label="名称"
                    fieldValue={shd.name}
                    labelStyle={styles.boldLabel}
                  />
                </Flex>
                <Flex>
                  <FlexTextField
                    label="序号"
                    fieldValue={shd.serial_no}
                    labelStyle={styles.boldLabel}
                  />
                  <FlexTextField
                    flex={2}
                    label="系统批次号"
                    fieldValue={shd.batch_no}
                    labelStyle={styles.boldLabel}
                  />
                  <NumbericInputItem
                    label="本次退料"
                    minValue={1}
                    maxValue={shd.ship_qty - shd.returned_qty}
                    value={shd.returning_qty}
                    onChange={(num) => {
                      if (Number.isNaN(num) || num === '' || num === null) {
                        return;
                      }
                      returnedStore.changeReturnDetail(
                        shd.id,
                        'returning_qty',
                        num,
                      );
                    }}
                  />
                </Flex>
              </List.Item>
            ))}
        </List>
      </ScrollView>
      <Flex>
        <Flex.Item>
          <MaterialScanButton
            buttonType={hasReturnings ? 'ghost' : 'primary'}
          />
        </Flex.Item>
        {hasReturnings ? (
          <Flex.Item>
            <RackConfirmButton
              onPressable={() => {
                if (!rackmatStore.shipRequester.tid) {
                  Toast.fail('请先识别退料人');
                  return false;
                }
                return true;
              }}
              rackActionText="退料"
              confirmText="确定退料到该架位"
              onConfirm={handleReturnConfirm}
            />
          </Flex.Item>
        ) : null}
      </Flex>
    </>
  );
}

AerialMaterialReturn.routeName = MaterialReturnRoute;
AerialMaterialReturn.permission = 'RMaterialReturn';

export default AerialMaterialReturn;
